package main

import (
    "os/signal"
    "time"
    "log"
    "os"
    "fmt"
    "syscall"
)

const (
    mainLogFile     = "/var/log/desktop_gateway.log"
    fatalLogFile    = "/var/log/desktop_gateway.fatal.log"
    debugLogFile    = "/var/log/desktop_gateway.debug"
    configFile      = "/etc/desktop-gateway/config.yaml"
)

var debugLog *RLog = nil
var mainLog *log.Logger = nil

func setupLog(file string) *log.Logger {
    f, err := os.OpenFile(file, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0777)
    if err != nil {
        fmt.Println("open log file failed.", err)
        return nil
    }
    return log.New(f, "", log.Ldate|log.Ltime)
}

func setupFatalLog() error {
    f, err := os.OpenFile(fatalLogFile, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0777)
    if err != nil {
        fmt.Println("open log file failed.", err)
        return err
    }
    syscall.Dup2(int(f.Fd()), int(os.Stderr.Fd()))
    return nil
}

func signalHandle() {
    for {
        sig := <- GSignal
        if sig == syscall.SIGHUP {
            mainLog.Println("reload...")
            loadConfig()
            reloadRdpProxyService()
            gTcpProxyServiceMgr.reloadService(getConfig().TcpProxy)
        }
    }
}

var GSignal = make(chan os.Signal, 1)

var Version = "1.0.5"
var PublishDate = "20210310"

func main() {
    if mainLog = setupLog(mainLogFile); mainLog == nil {
        return
    }

    if setupFatalLog() != nil {
        return
    }
    
    debugLog = openRLog(debugLogFile)
    RLogRun()
    
    configInit()
    loadConfig()
    
    TcpProxyServiceMgrInit()
    DeskTopClientMgrInit()
    SoftwareMgrInit()
    
    startRdpProxyService()
    gTcpProxyServiceMgr.startService(getConfig().TcpProxy)
    
    startHttpProxy()

    HttpApiServiceStart()
    
    go signalHandle()
    signal.Notify(GSignal, syscall.SIGHUP)
    
    mainLog.Println("running...")
    mainLog.Printf("当前版本号:%s 发布日期:%s\n", Version, PublishDate)

    for {
        time.Sleep(time.Second * 3)
    }
}